---
import { Icon } from "astro-icon/components";
import { announcementConfig } from "@/config/announcementConfig";
import I18nKey from "@/i18n/i18nKey";
import { i18n } from "@/i18n/translation";
import WidgetLayout from "./WidgetLayout.astro";

const config = announcementConfig;

interface Props {
  class?: string;
  style?: string;
}
const className = Astro.props.class;
const style = Astro.props.style;
---

<!-- 组件显示现在由sidebarLayoutConfig统一控制，无需检查config.enable -->
<WidgetLayout
  name={config.title || i18n(I18nKey.announcement)}
  id="announcement"
  class={className}
  style={style}
>
  <div>
    <!-- 公告栏内容 -->
    <div class="text-neutral-600 dark:text-neutral-300 leading-relaxed mb-3">
      {config.content}
    </div>

    <!-- 可选链接和关闭按钮 -->
    <div class="flex items-center justify-between gap-3">
      <div>
        {
          config.link && config.link.enable !== false && (
            <a
              href={config.link.url}
              target={config.link.external ? "_blank" : "_self"}
              rel={config.link.external ? "noopener noreferrer" : undefined}
              class="btn-regular rounded-lg px-3 py-1.5 text-sm font-medium active:scale-95 transition-transform"
            >
              {config.link.text}
            </a>
          )
        }
      </div>

      {
        config.closable && (
          <button
            class="btn-regular rounded-lg h-8 w-8 text-sm hover:bg-red-100 dark:hover:bg-red-900/30 transition-colors"
            onclick="closeAnnouncement()"
            aria-label={i18n(I18nKey.announcementClose)}
          >
            <Icon name="fa6-solid:xmark" class="text-sm" />
          </button>
        )
      }
    </div>
  </div>
</WidgetLayout>

<script>
  function closeAnnouncement() {
    // 通过data-id属性找到整个widget-layout元素
    const widgetLayout = document.querySelector(
      'widget-layout[data-id="announcement"]'
    );
    if (widgetLayout) {
      // 隐藏整个widget-layout元素
      widgetLayout.style.display = "none";
      // 保存关闭状态到localStorage
      localStorage.setItem("announcementClosed", "true");
    }
  }

  // 页面加载时检查是否已关闭
  document.addEventListener("DOMContentLoaded", function () {
    const widgetLayout = document.querySelector(
      'widget-layout[data-id="announcement"]'
    );
    if (widgetLayout && localStorage.getItem("announcementClosed") === "true") {
      widgetLayout.style.display = "none";
    }
  });

  // 使公告栏函数全局可用
  window.closeAnnouncement = closeAnnouncement;
</script>
